import React, { useEffect } from "react";
import { Form, Input, Button, Spin, message, Upload } from "antd";
import { getUserInfo, updateUserInfo } from "../network/api";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { useState } from "react";
import "./less/personal.less";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default function Personal() {
  let [isLoading, setLoading] = useState(false);
  let [imgLoading, setImgLoading] = useState(false);
  let [imageUrl, setImgUrl] = useState("");
  let [userInfo, setUserInfo] = useState({});
  const [form] = Form.useForm();

  //
  function beforeUpload(file) {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error(" 只能上传格式为 JPG/PNG 文件!");
    }
    const isLt2M = file.size / 1024 < 200;
    if (!isLt2M) {
      message.error("图片必须小于200kb!");
    }
    return isJpgOrPng && isLt2M;
  }

  const handleChange = (info) => {
    if (info.file.status === "uploading") {
      setImgLoading(true);
      return;
    }
    if (info.file.status === "done") {
      getBase64(info.file.originFileObj, (imageUrl) => {
        setImgLoading(false);
        setImgUrl(imageUrl);
      });
    }
  };

  // 获取用户资料
  const getUserInfoDone = async () => {
    try {
      setLoading(true);
      const result = await getUserInfo();
      if (!result.errCode) {
        let {
          data: { username, password, avatar },
        } = result;
        message.success("用户资料获取成功!");
        form.setFieldsValue({
          username,
          password,
        });
      }
    } catch (error) {
      console.log("error: ", error);
    }
    setLoading(false);
  };
  // mounted
  useEffect(() => {
    getUserInfoDone();
  }, []);

  // 提交
  const onFinish = async (values) => {
    isLoading = setLoading(true);
    try {
      const result = await updateUserInfo(values);
      console.log("result: ", result);
      if (!result.errCode) {
        message.success("个人资料修改成功");
      }
    } catch (error) {
      console.log("error: ", error);
    }
    isLoading = setLoading(false);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div className="personal-box">
      <Form
        form={form}
        name="basic"
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: "请输入新用户名!",
            },
          ]}
        >
          <Input placeholder="请输入新用户名" size="large" />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: "请输入新密码!",
            },
          ]}
        >
          <Input.Password placeholder="请输入新密码" size="large" />
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            size="middle"
            htmlType="submit"
            className="submit-btn"
          >
            提交
          </Button>
        </Form.Item>
      </Form>

      {/* 头像 */}
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="/api/upload"
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl ? (
          <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
        ) : (
          <div>
            {imgLoading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传</div>
          </div>
        )}
      </Upload>
    </div>
  );
}
